from tools.ffz_pcap_reader.ffz_packet import MyPacket
from tools.ffz_pcap_reader.pcap_exception import PcapReadException


def create_packet(stream, byte_order):
    header = stream.read(16)
    if not header:
        return None
    # 例子如下：小端序的存储为 42 00 00 00 从左到右地址分别为： 0x20 0x21 0x22 0x23
    # 读取出来的十进制是66
    dataLen = int.from_bytes(header[8: 12], byteorder=byte_order, signed=False)
    data = stream.read(dataLen)
    return MyPacket(header, data)


def macstr2bytes(config_srcmac: str) -> bytes:
    ans = []
    mac_val_arr = config_srcmac.split(':')
    for ele in mac_val_arr:
        ans.append(int(ele, 16))
    return bytes(ans)


class PcapReader:

    def __init__(self):
        pass

    def read(self, pcap_path, config_srcmac):
        try:
            config_srcmac = macstr2bytes(config_srcmac)
            stream = open(pcap_path, "rb")
            pcap_header = stream.read(24)
            byte_order: str
            if pcap_header[:4] == b'\xd4\xc3\xb2\xa1':
                byte_order = "little"
            elif pcap_header[:4] == b'\xa1\xb2\xc3\xd4':
                byte_order = "big"
            else:
                raise PcapReadException("Magic 读取错误")
        except PcapReadException as e:
            print(e.msg)
            return

        client_packets = []
        server_packets = []
        packets = []
        while True:
            packet = create_packet(stream, byte_order)
            if packet is not None:
                packets.append(packet)
            else:
                break
        for packet in packets:
            packet: MyPacket
            if packet.mac_layer.get_src_mac() == config_srcmac:
                client_packets.append(packet)
            else:
                server_packets.append(packet)
        return client_packets, server_packets
